package job

import (
	"scheduler/dal"
	"time"

	log "github.com/omidnikta/logrus"
)

var (
	AllJobs map[string]*Job
)

func LoadAllJobs() error {
	jobs, err := dal.JobModel().GetAll()
	if nil != err {
		log.Errorln(err)
		return err
	}

	//从数据库格式转换为程序数据结构
	AllJobs = make(map[string]*Job, len(jobs))
	for _, j := range jobs {
		var job Job
		job.ID = j.ID

		tasks := make(map[string]*Task, len(j.Tasks))
		for _, t := range j.Tasks {
			var action Action
			action.Addr = t.Addr
			action.Path = t.Path
			action.Body = t.Body

			var task Task
			task.ID = t.ID
			task.Retry = t.Retry
			task.StartAt = DurationToTime(time.Duration(t.StartAt))
			task.Action = &action

			tasks[task.ID] = &task
		}
		job.Tasks = tasks

		AllJobs[job.ID] = &job
	}

	return nil
}

func Run() {
	err := LoadAllJobs()
	if nil != err {
		log.Error(err)
		return
	}

	for _, j := range AllJobs {
		j.Run()
	}
}

func AddJob(id string) {
	modelJob, err := dal.JobModel().Get(id)
	if nil != err {
		log.Errorln(err)
		return
	}

	job := ModelJobToJob(modelJob)
	AllJobs[job.ID] = job

	go job.Run()
}
